package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    private static final String PAGE_INDEX = "admin/index";
    private static final String PAGE_DELETE = "redirect:/admin";
    @Reference
    private AdminService adminService;

    @RequestMapping
    public String index(@RequestParam Map<String,Object> filters, Model model){
        //1. 判断是否传入了pageNum和pageSize，如果没有，则赋默认值
        if (filters.get("pageNum") == null || "".equals(filters.get("pageNum"))) {
            filters.put("pageNum",1);
        }
        if (filters.get("pageSize") == null || "".equals(filters.get("pageSize"))) {
            filters.put("pageSize",10);
        }
        //2. 调用业务层的方法查询分页数据
        PageInfo<Admin> pageInfo = adminService.findPage(filters);
        //3. 将查询到的分页数据存入请求域
        model.addAttribute("page",pageInfo);
        //4. 将搜索条件存入请求域
        model.addAttribute("filters",filters);
        //5. 显示首页
        return PAGE_INDEX;
    }
    @PostMapping("/save")
    public String save(Admin admin,Model model){
        adminService.insert(admin);
        return successPage(model, "添加用户成功！");
    }
    private final static String PAGE_EDIT = "admin/edit";
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id,Model model){
        Admin admin = adminService.getById(id);
        model.addAttribute("admin",admin);
        return PAGE_EDIT;
    }
    @PostMapping("/update")
    public String update(Admin admin,Model model){
        adminService.update(admin);
        return successPage(model,"修改用户成功！");
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id){
        adminService.delete(id);
        return PAGE_DELETE;
    }

}
